<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/26
 * Time: 9:16
 */

namespace app\qgroup\service;


use app\common\Enum\CommonEnum;
use app\qgroup\model\PowerfulList;
use think\Exception;

class PowerfulService
{
    /**
     * 获取功能
     * @param $name string 功能名称
     * @return string
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public static function get($name)
    {
        if (cache('?power_list_cache') && isset(cache('power_list_cache')[$name])){
            return cache('power_list_cache')[$name];
        }else{
            $code = '';
            self::init($name,$code);
            if ($code == ''){
                throw new Exception('无此功能');
            }
            return $code;
        }
    }

    /**
     * 获取所有功能
     * @return mixed
     * @throws \think\exception\DbException
     */
    public static function all()
    {
        if (!cache('?power_list_cache')) {
            self::init();
        }
        return cache('power_list_cache');
    }

    /**
     * 初始化功能列表缓存
     * @param string $name
     * @param string $code
     * @throws \think\exception\DbException
     */
    private static function init($name = '',&$code = ''){
        $pls = PowerfulList::all(['status'=>CommonEnum::COMMON_VALID]);
        $res = [];
        foreach ($pls as $pl){
            $res[$pl->name] = $pl->code;
            if ($name == $pl->name){
                $code = $pl->code;
            }
        }
        cache('power_list_cache',$res);
    }
}